package com.product.shiro;

//import com.coalSystem.entity.UserLogin;
//import com.coalSystem.service.UserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

// https://blog.csdn.net/sqlgao22/article/details/99186391

/**
 * 用户登录
 */
@Slf4j
@Component
public class MyRealm extends AuthorizingRealm {
//    @Resource
//    private UserLoginService userLoginService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("============用户授权==============");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        /*获取当前的用户,已经登录后可以使用在任意的地方获取用户的信息*/
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        /*查询用户的权限*/
//        UserLogin userLogin = userLoginService.getRole(username);
//        /*将role放在一个集合中,多个权限使用集合*/
//        info.addRole(userLogin.getRole());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("============用户验证==============");
        //从token中获取信息,此token只是shiro用于身份验证的,并非前端传过来的token.
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
//        UserLogin userLogin = userLoginService.getRole(username);
        // 用户不存在
//        if(userLogin ==null) throw new AuthenticationException("用户不存在");
//        String password = userLogin.getPassword();
//        log.info("用户密码：{}",password);
//
//        if (null == password) {
//            // 存在用户，但密码为空（用户异常）
//            throw new AuthenticationException("密码为空");
//        } else if (!password.equals(new String(token.getPassword()))) {
//            // 账户登录密码错误
//            throw new AuthenticationException("密码错误");
//        }
        //组合一个验证信息
        log.info("token.getPrincipal()默认返回的username======" + token.getPrincipal());
        log.info("getName()" + getName());
        String password = "aa";
        SimpleAuthenticationInfo info =
                new SimpleAuthenticationInfo(token.getPrincipal(), password, getName());
        return info;
    }
}

